<template>
  <div class="app-container">

    <div class="filter-container" style="padding: 5px">
      <div style="display: flex;align-items: center;padding: 10px;">
        <div style="font-size: 18px;color: #333333;font-weight: bold">
          模板名称
        </div>
        <div style="flex: 1;font-size: 14px;color: #999999;padding: 0 10px">
          <p>
            {{ $route.params.name }}
          </p>

        </div>
        <div>
          <el-button ref="zoomOut" size="small" type="primary" class="noimpor-btn" @click="zoomOut"><i
            class="el-icon-zoom-out"
          /></el-button>
          <el-button ref="zoomIn" size="small" type="primary" class="noimpor-btn" @click="zoomIn"><i
            class="el-icon-zoom-in"
          /></el-button>
          <el-button ref="zoomIn" size="small" type="primary" class="noimpor-btn" @click="saveMind"><i
            class="el-icon-upload"
            style="margin-right: 8px"
            v-bp="'/bs/template/edit'"
          />保存
          </el-button>
        </div>
      </div>

    </div>
    <div
      style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;"
    >
      <div class="jsmindbox">

        <div id="jsmind" />

      </div>
    </div>

    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" title="修改排序" :visible.sync=" dialogPxVisible">
     <el-input type="number" v-model="px" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPxVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="subPx">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" title="选择网络文件" :visible.sync="dialogFormVisible">
      <el-select v-model="fileType">
        <el-option value="SPM" label="SPM"></el-option>
        <el-option value="EPM" label="EPM"></el-option>
        <el-option value="DWI" label="DWI"></el-option>
        <el-option value="cadDir" label="图纸"></el-option>
        <el-option value="MIS+" label="MIS+"></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="addFile">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" title="选择其它类型" :visible.sync="otherFormVisible">
      <el-select v-model="otherType">
        <el-option value="Process Key parts" label="Process Key parts"></el-option>
        <el-option value="reuse/relocation record" label="reuse/relocation record"></el-option>
        <el-option value="process/parts change list" label="process/parts change list"></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="otherFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="addOtherFile">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getTemplateList, saveTemplate } from '@/api/template'
import * as _ from 'lodash'
import jsMind from "@/views/bs/JsMind/JsMind.vue";
require('../../assets/js/jsmind.menu.js')
import '@/views/bs/JsMind/jsmind.css'
import '@/views/bs/JsMind/jsmind.draggable.js'
import '@/views/bs/JsMind/jsmind.screenshot.js'
import uuid from 'uuid'
import CyTreeSelect from '@/components/CyTreeSelect.vue'
import { deleteNode } from '@/api/template'
import Pagination from "@/components/Pagination/index.vue";
import {fetchList} from "@/api/common";
window.uuid = uuid

window.nodedata = {
  id: '1', // [必选] ID, 所有节点的ID不应有重复，否则ID重复的结节将被忽略
  topic: '新建文件夹', // [必选] 节点上显示的文字
  direction: 'right', // [可选] 节点的方向，此数据仅在第一层节点上有效，目前仅支持 left 和 right 两种，默认为 right
  expanded: true, // [可选] 该节点是否是展开状态，默认为 true
  inc_type: 'dir', // 文件类型 dir为文件夹
  nodetype: 'dir',
  background_color: '#027ABC', // 背景色 这个可以考虑保存下。方便以后分辨不同作用或类形的文件
  foreground_color: '#ffffff', // 蚊子色 这个可以考虑保存下。方便以后分辨不同作用或类形的文件
  'background-color': '#027ABC', // 背景色 这个可以考虑保存下。方便以后分辨不同作用或类形的文件
  'foreground-color': '#ffffff', // 蚊子色 这个可以考虑保存下。方便以后分辨不同作用或类形的文件
  promise: [{ // 权限，对应权限表中的数据
    id: '',
    doc_id: '',
    uu_id: '',
    inc_type: '',
    role_id: '',
    is_read: '',
    is_write: '',
    user_id: '',
    is_display: ''
  }],
  children: [],

}

export default {
  name: 'EditTemplate',
  components: {Pagination, CyTreeSelect },
  data() {
    return {

      jm: null,
      otherFormVisible:false,
      otherType:"",
      dialogFormVisible: false,
      dialogPxVisible:false,
      selectedNode: null,
      fileType: '',
      user: null,
      // id:null,
      drawer: false,
      dialogVisible: false,
      direction: 'rtl',
      selectVal: [],
      theme_value: 'primary',
      nodeOption: {
        content: '',
        bgColor: '',
        fontColor: '',
        fontSize: '',
        fontWeight: '',
        fontStyle: ''
      },

      mindHeight: '100vh',
      themOptions: ['primary', 'warning', 'danger', 'success', 'info', 'greensea', 'nephrite', 'belizehole', 'wisteria', 'asphalt', 'orange', 'pumpkin', 'pomegranate', 'clouds', 'asbestos'],
      mind: {
        meta: {
          name: 'jsMind remote',
          author: 'hizzgdev@163.com',
          version: '0.2'
        },
        format: 'node_tree',
        data: {}
      },
      options: {
        container: 'jsmind', // [必选] 容器的ID
        editable: true, // [可选] 是否启用编辑
        theme: 'orange', // [可选] 主题
        support_html: true,
        view: {
          engine: 'canvas', // 思维导图各节点之间线条的绘制引擎
          hmargin: 100, // 思维导图距容器外框的最小水平距离
          vmargin: 50, // 思维导图距容器外框的最小垂直距离
          line_width: 2, // 思维导图线条的粗细
          line_color: '#555' // 思维导图线条的颜色
        },
        layout: {
          hspace: 30, // 节点之间的水平间距
          vspace: 20, // 节点之间的垂直间距
          pspace: 13 // 节点与连接线之间的水平间距（用于容纳节点收缩/展开控制器）
        },
        userOpiotn:{
          editnetwork:this.editNetWorkFile,
          editother:this.editOtherFile,
        },
        menuOpts: {
          showMenu: true,
          tipContent: '请选中节点！！！',
          dir_right_menu: [

            {
              target: 'addChild', text: '添加文件夹',
              callback: this.addDir,
              fun: () => {
              }
            },
            {
              target: 'addChild', text: '添加网络文件',
              callback: this.addNetWorkFile,
              fun: () => {
              }
            },
            {
              target: 'addChild', text: '添加其它',
              callback: this.addother,
              fun: () => {
              }
            },
            {
              target: 'edit', text: '编辑名称',
              callback: function(node) {
                console.log(node)
              }
            },
            {
              target: 'edit', text: '修改排序',
              callback: this.editPx,
            },
            // {
            //   target: 'addBrother', text: '添加平级',
            //   callback: function(node) {
            //     console.log(node)
            //   }
            // },
            {
              target: 'delete', text: '删除文件夹',
              callback: this.delDir,
              fun: () => {
              }
            },

            {
              target: 'showAll', text: '展开文件夹',
              callback: function(node, next) {
                console.log(node)
              }
            },
            {
              target: 'hideAll', text: '收起文件夹',
              callback: function(node, next) {
                console.log(node)
              }
            }
          ],
          file_right_menu: [
            {
              target: 'edit', text: '编辑名称',
              callback: this.editNodeType,
              fun: () => {
              }
            },
            {
              target: 'delete', text: '删除文件',
              callback: this.delDir,
              fun: () => {
              }
            }
          ],
          injectionList: []
        },
        shortcut: {
          enable: false,
          handles: {},
          mapping: {
            addchild: 45, // Insert
            addbrother: 13, // Enter
            editnode: 113, // F2
            delnode: 46, // Delete
            toggle: 32, // Space
            left: 37, // Left
            up: 38, // Up
            right: 39, // Right
            down: 40 // Down
          }
        }
      },
      issave: 'true',
      isdelete: 'false',
      formData: {
        id: '',
        // mindCode: '',
        mindName: '',
        // mindType: '',
        mindData: '',
        mindOptions: ''
      },

      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },

      isShow: true,
      isLoad: false,
      selectNode: null,
      px:0,
      isedit:null,
    }

  },

  mounted() {
    this.jm = window.jsMind
    this.$nextTick(() => {
      this.getTemplate()
    })

  },
  beforeRouteLeave(to,from,next)
  {
    if(this.$store.getters.buttons.indexOf('/bs/template/view')!==-1)
    {
      this.$confirm("您是否需要保存模板").then(()=>{
        this.saveMind();
      }).finally(()=>{
        next();
      })
    }


  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    subbj(){
      if(this.multipleSelection.length==0)
      {
        this.$message.error("请选择要添加的备件")
        return
      }

      this.multipleSelection.forEach((item)=>{

        var newnode = _.cloneDeep(window.nodedata)
        newnode.topic = item.name
        newnode.id = uuid()
        newnode.parent_id = this.selectedNode.id
        newnode.doc_id = this.$route.params.id
        newnode.promise[0].uu_id = newnode.id
        newnode.nodetype = 'file'
        newnode.inc_type = 'sp'
        newnode.path=item.id
        this.jm.add_node(this.selectedNode, newnode.id, newnode.topic, newnode)
        this.jm.set_node_color(newnode.id, '#cc3300', '#ffffff')

      })

      console.log(this.multipleSelection)


      this.selectbj=false;


    },
    getStationList(){
      this.listLoading = true
      fetchList({  page_no: 1,
        limit: 100,
        sort: 'id',}, 'sl_view_station').then(response => {
        if (response.data && response.data.items) {
          this.station_list = response.data.items
        }
        this.listLoading = false
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery, 'spare_parts').then(response => {
        if (response.data && response.data.items) {
          this.list = response.data.items
          this.total = response.data.count
        }
        this.listLoading = false
      })
    },

    doEditOtherFile(){
      this.jm.update_node( this.isedit.id, this.otherType)
      this.isedit=null;
      this.otherFormVisible=false;
    },


    editFile(){
      console.log("有没有")
        this.jm.update_node( this.isedit.id, this.fileType)
      this.isedit=null;
      this.dialogFormVisible=false;
    },
    editNodeType(node){
      // let jump=['EPM','SPM','MIS+','DWI','cadDir']
      // if(node&&node.data)
      // {
      //   if(jump.indexOf(node.data.inc_type)!=-1)
      //   {
      //     this.editNetWorkFile(node)
      //     return false
      //   }
      // }


    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)

      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          console.log('查询', listkeys[i], isNaN(listkeys[i]))
          let operator = '='
          let value = this.listQuery[listkeys[i]]
          if (!this.queryMap[listkeys[i]]) {
            if (isNaN(listkeys[i])) {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          } else {
            if (this.queryMap[listkeys[i]] == 'like') {
              operator = 'like'
              value = '%' + this.listQuery[listkeys[i]] + '%'
            }
            if (!queryParma['and']) {
              queryParma['and'] = []
            }
            queryParma['and'].push({ field: listkeys[i], operator: operator, value: value })
          }
        }
      }
      this.list = []
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleFilterReset() {
      this.listQuery = {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      }
      this.getList()
    },

    editOtherFile(node){
      this.isedit=node;
      this.otherType=node.data.inc_type
      this.otherFormVisible=true;
      console.log("获取到的节点",node)
    },


    editNetWorkFile(node){
      this.isedit=node;
      this.fileType=node.topic
      this.dialogFormVisible=true;
      console.log("获取到的节点",node)
    },

    tipmessage(e){
      // console.log("有事件")
      // e.preventDefault();
      // e.returnValue='';
      // if(window.confirm("x"))
      // {
      //
      // }
      //
      //
      // return false;
    },
    getTemplate() {
      getTemplateList(this.$route.params.id).then((res) => {
        if (!res.data) {
          var node = _.cloneDeep(window.nodedata)
          node.id = uuid()
          node.topic = '根目录'
          node.doc_id = this.$route.params.id
          node.promise[0].uu_id = node.id
          console.log('添加', node)
          this.mind.data = node
          this.jm = this.jm.show(this.options, this.mind)
        } else {
          this.convertData(res.data[0])
          this.mind.data = res.data[0]
          this.jm = this.jm.show(this.options, this.mind)
        }
      })
    },
    convertData(data) {
      data['background-color'] = data['background_color']
      data['foreground-color'] = data['foreground_color']
      data['promise'] = [data['promise']]
      console.log(data)

      if (data.children && data.children.length > 0) {
        for (var i = 0; i < data.children.length; i++) {
          this.convertData(data.children[i])
        }
      }
    },

    addChild(node) {
      console.log('甲硝唑调')
      // this.jm.add_node(node,uuid(),"新建文件夹")
    },
    addSpareParts(node) {
      this.selectedNode=node;
      this.selectbj=true;
    },
    addDir(node) {
      var newnode = _.cloneDeep(window.nodedata)
      newnode.topic = '新建文件夹'
      newnode.id = uuid()
      newnode.parent_id = node.id
      newnode.doc_id = this.$route.params.id
      newnode.promise[0].uu_id = newnode.id
      this.jm.add_node(node, newnode.id, newnode.topic, newnode)
    },
    delDir(node) {
      deleteNode(node.id).then(() => {
        this.jm.remove_node(node)
      })
    },
    editPx(node)
    {  this.selectedNode = node
      this.dialogPxVisible = true
    },
    addNetWorkFile(node) {
      this.selectedNode = node
      this.dialogFormVisible = true
    },


    subPx(){
      if (this.px=='') {
        this.$message.error('请输入排序')
        return
      }
      this.selectedNode.data['px']=parseInt(this.px)
      this.jm.update_node(this.selectedNode.id,this.selectedNode.topic,this.selectedNode)
      this.dialogPxVisible=false;
    },
    addother(node){
      this.selectedNode = node
      this.otherFormVisible = true
    },

    addOtherFile() {

      if(this.isedit){
        this.doEditOtherFile();
        return;
      }

      if (!this.otherType) {
        this.$message.error('请选择文件类型')
        return
      }



      var newnode = _.cloneDeep(window.nodedata)
      newnode.topic = 'Process Key parts'
      if(this.otherType=='relocation'){
        newnode.topic = 'reuse/relocation record'
      }
      if(this.otherType=='parts'){
        newnode.topic = 'process/parts change list'
      }
      newnode.id = uuid()
      newnode.parent_id = this.selectedNode.id
      newnode.doc_id = this.$route.params.id
      newnode.nodetype = 'file'
      newnode.inc_type = this.otherType
      newnode.background_color = '#cc3300'
      newnode.promise[0].uu_id = newnode.id
      this.jm.add_node(this.selectedNode, newnode.id, newnode.topic, newnode)
      this.jm.set_node_color(newnode.id, '#cc3300', '#ffffff')
      this.otherFormVisible=false;
    },

    addFile() {
      console.log("添回")

      if(this.isedit){
        this.editFile();
        return;
      }

      if (!this.fileType) {
        this.$message.error('请选择文件类型')
        return
      }
      var newnode = _.cloneDeep(window.nodedata)
      newnode.topic = this.fileType
      newnode.id = uuid()
      newnode.parent_id = this.selectedNode.id
      newnode.doc_id = this.$route.params.id
      newnode.nodetype = 'file'
      newnode.background_color = '#cc0033'
      newnode.inc_type = this.fileType
      newnode.promise[0].uu_id = newnode.id

      this.jm.add_node(this.selectedNode, newnode.id, this.fileType, newnode)
      this.jm.set_node_color(newnode.id, '#cc0033', '#ffffff')
      this.selectedNode = null
      this.dialogFormVisible = false
      this.fileType = ''
    },

    // 缩小
    zoomOut() {
      if (this.jm.view.zoomOut()) {
        this.$refs.zoomOut.disabled = false
      } else {
        this.$refs.zoomOut.disabled = true
      }
      this.$refs.zoomIn.disabled = false
    },
    // 放大
    zoomIn() {
      if (this.jm.view.zoomIn()) {
        this.$refs.zoomIn.disabled = false
      } else {
        this.$refs.zoomIn.disabled = true
      }
      this.$refs.zoomOut.disabled = false
    },
    // 新增节点
    addNode() {
      const selectedNode = this.jm.get_selected_node() // as parent of new node
      if (!selectedNode) {
        this.$message({
          type: 'warning',
          message: '请先选择一个节点!'
        })
        return
      }
      const nodeid = this.jsMind.util.uuid.newid()
      const topic = 'new Node'
      this.jm.add_node(selectedNode, nodeid, topic)
    },
    // 编辑节点
    editNode() {
      const selectedId = this.get_selected_nodeid()
      if (!selectedId) {
        this.$message({
          type: 'warning',
          message: '请先选择一个节点!',
          duration: 1000
        })
        return
      }
      const nodeObj = this.jm.get_node(selectedId)
      this.nodeOption.content = nodeObj.topic
      this.nodeOption.bgColor = nodeObj.data['background-color']
      this.nodeOption.fontColor = nodeObj.data['foreground-color']
      this.nodeOption.fontSize = nodeObj.data['font-size']
      this.nodeOption.fontWeight = nodeObj.data['font-weight']
      this.nodeOption.fontStyle = nodeObj.data['font-style']
      this.dialogVisible = true
    },
    sureEditNode() {
      const selectedId = this.get_selected_nodeid()
      this.jm.update_node(selectedId, this.nodeOption.content)
      this.jm.set_node_font_style(selectedId, this.nodeOption.fontSize, this.nodeOption.fontWeight, this.nodeOption.fontStyle)
      this.jm.set_node_color(selectedId, this.nodeOption.bgColor, this.nodeOption.fontColor)
      this.nodeOption = {
        content: '',
        bgColor: '',
        fontColor: '',
        fontSize: '',
        fontWeight: '',
        fontStyle: ''
      }
      this.dialogVisible = false
    },
    // 删除节点
    onRemoveNode() {
      const selectedId = this.get_selected_nodeid()
      if (!selectedId) {
        this.$message({
          type: 'warning',
          message: '请先选择一个节点!'
        })
        return
      }
      this.jm.remove_node(selectedId)
    },
    // 布局方向
    changeOption() {
      if (this.options.mode === 'side') {
        this.options = {
          mode: 'full'
        }
      } else {
        this.options = {
          mode: 'side'
        }
      }
    },
    // 选择主题颜色
    set_theme() {
      this.jm.set_theme(this.theme_value)
    },
    // 获取选中标签的 ID
    get_selected_nodeid() {
      const selectedNode = this.jm.get_selected_node()
      if (selectedNode) {
        return selectedNode.id
      } else {
        return null
      }
    },
    getMind() {
      // this.$axios.get('get_mind_id',{
      //   params:{
      //     id:this.formData.id
      //   }
      // }).then((res) => {
      this.formData = res.data
      console.log(res.data)
      if (this.formData.mindOptions !== '') {
        this.theme_value = JSON.parse(this.formData.mindOptions).theme
        this.set_theme()
      }
      this.jm.show(JSON.parse(res.data.mindData))
      // }).catch(err => {
      //   console.log(err)
      // })
    },
    eachTree(tree)
    {
      if(!tree.px)
      {
        tree.px=0;
      }else{
        tree.px=parseInt(tree.px)
      }
      if(tree.children)
      {
        tree.children.forEach((item)=>{
          this.eachTree(item)
        })

      }
    },

    saveMind() {
      var data = this.jm.get_data()
      data = data.data
      console.log('提交的数据', data)
      this.eachTree(data)
      saveTemplate(data).then((res) => {
        if (res.code == 0) {
          this.$message.success('保存成功')
        }
        console.log(res)
      })
    },
    deleteMind() {
      this.$confirm('您确定要删除该导图吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'delete_mind_id'
        this.$axios.get(url, {
          params: {
            id: this.formData.id
          }
        }).then((res) => {
          const result = res.data
          if (result === '删除成功') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          this.$router.push('/jsmind')
          location.reload()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped>

.jsmindbox {
  width: 100%;
  height: calc(100vh - 300px);
  overflow: auto;
  display: flex;
  flex-direction: column;
}

#jsmind {
  flex: 1;
}

/*body{*/
/*  padding: 10px;*/
/*  margin: 0px;*/
/*}*/
/*.header{*/
/*  height: 40px;*/
/*  background-color: #eee;*/
/*  border-bottom: solid 1px #aaa;*/
/*  z-index: 100;*/
/*}*/
.el-main {
  padding: 0;
}

.el-header {
  padding: 10px;
  width: 100%;
  height: 40px !important;
  display: flex;
  /*line-height: 40px;*/
  align-items: center;
  z-index: 3;
  position: fixed;
  margin-top: 10px;

}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 30px;
  overflow: hidden;
  background-color: #f2f2f2;
  border-top: solid 1px #bbb;
}

.user_phone {
  line-height: 40px;
  width: 80px;
  height: 40px;
}

</style>
